//CartServlet.java
package com.ylaihui.web;

import com.google.gson.Gson;
import com.sun.xml.internal.bind.v2.model.core.ID;
import com.ylaihui.pojo.Book;
import com.ylaihui.pojo.Cart;
import com.ylaihui.pojo.CartItem;
import com.ylaihui.service.BookService;
import com.ylaihui.service.impl.BookServiceImpl;
import com.ylaihui.utils.WebUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author lisimmy www.ylaihui.com
 * @create 2021-08-03
 */
public class CartServlet extends BaseServlet {
    BookService bookService = new BookServiceImpl();

    protected void addItem(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //System.out.println("add item succ.");
        //System.out.println(req.getParameter("id"));
        // 获取商品的ID
        int id = WebUtils.parseInt(req.getParameter("id"), 0);

        // 通过ID 获取商品信息
        Book book = bookService.queryBookById(id);

        // 将商品信息（商品对象）转换为 购物车中的 Item
        CartItem cartItem = new CartItem(book.getId(), book.getName(), 1, book.getPrice(), book.getPrice());

        // 将 Item 添加到购物车对象 Cart 中
        //每次添加购物车，不能每次都要new Cart对象，因此将第一次new 的 Cart 对象存放到session 域中
        Cart sessionCart = (Cart) req.getSession().getAttribute("cart");
        if (sessionCart == null) {
            sessionCart = new Cart();
            req.getSession().setAttribute("cart", sessionCart);
        }
        sessionCart.addItem(cartItem);

        System.out.println(book.getName() + " add Cart Succ.");
        req.getSession().setAttribute("lastName", cartItem.getName());

        // 请求重定向到 浏览器的原来请求页面
        resp.sendRedirect(req.getHeader("Referer"));
    }

    /**
     * ajax 添加购物车功能
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void ajaxAddItem(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 获取商品的ID
        int id = WebUtils.parseInt(req.getParameter("id"), 0);

        // 通过ID 获取商品信息
        Book book = bookService.queryBookById(id);

        // 将商品信息（商品对象）转换为 购物车中的 Item
        CartItem cartItem = new CartItem(book.getId(), book.getName(), 1, book.getPrice(), book.getPrice());

        // 将 Item 添加到购物车对象 Cart 中
        //每次添加购物车，不能每次都要new Cart对象，因此将第一次new 的 Cart 对象存放到session 域中
        Cart sessionCart = (Cart) req.getSession().getAttribute("cart");
        if (sessionCart == null) {
            sessionCart = new Cart();
            req.getSession().setAttribute("cart", sessionCart);
        }
        sessionCart.addItem(cartItem);

        System.out.println(book.getName() + " add Cart Succ.");
        req.getSession().setAttribute("lastName", cartItem.getName());

        Gson gson = new Gson();
        Map<String, Object> result = new HashMap<String, Object>();

        result.put("totalCount",sessionCart.getTotalCount());
        result.put("lastName", book.getName());

        String s = gson.toJson(result);
        resp.getWriter().write(s);
    }


    /**
     * 删除购物车对象中的商品项
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void deleteItem(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 获取商品的id
        String id = req.getParameter("id");
        int i = WebUtils.parseInt(id, 0);

        //获取 session 中的购物车对象
        Cart cart = (Cart) req.getSession().getAttribute("cart");
        if (cart != null) {
            //删除购物车中的对象
            cart.deleteItem(i);
        }
        // 请求重定向到 浏览器的原来请求页面
        resp.sendRedirect(req.getHeader("Referer"));
    }

    /**
     * 清空购物车
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void clearItem(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Cart cart = (Cart) req.getSession().getAttribute("cart");

        if (cart != null) {
            cart.clear();
        }
        // 请求重定向到 浏览器的原来请求页面
        resp.sendRedirect(req.getHeader("Referer"));
    }


    /**
     * 修改购物车中商品的数量
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void updateCount(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int id = WebUtils.parseInt(req.getParameter("id"), 0);
        int count = WebUtils.parseInt(req.getParameter("count"), 0);

        Cart cart = (Cart) req.getSession().getAttribute("cart");
        if (cart != null) {
            cart.updateCount(id, count);
        }
        // 请求重定向到 浏览器的原来请求页面
        resp.sendRedirect(req.getHeader("Referer"));
    }
}
